package com.ws.util;


import java.lang.reflect.Constructor;
import java.lang.reflect.Field;

/**
 * @author 王硕
 * @version jdk21
 * @className ReflectionCreateObject
 * @description
 * @date 2024/12/2 20:14
 */
public class ReflectionGetField {
    public static void main(String[] args) {
        try {
            // 获取Class对象
            Class<Person> personClass = Person.class;

            Person person = personClass.getDeclaredConstructor().newInstance();

            // 获取私有字段name的Field对象
            Field nameField = personClass.getDeclaredField("name");
            // 获取私有字段age的Field对象
            Field ageField = personClass.getDeclaredField("age");
            nameField.setAccessible(true);
            ageField.setAccessible(true);
            nameField.set(person,"小明");
            ageField.set(person,30);
            person.test();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
